package com.kk.controller;

import com.kk.model.Menu;
import com.kk.model.User;
import com.kk.repository.RoleMenuRelRepository;
import com.kk.repository.UserRepository;
import com.kk.service.UserService;
import com.kk.shiro.JwtUtil;
import com.kk.util.redis.RedisUtils;
import com.kk.util.result.Result;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleMenuRelRepository roleMenuRelRepository;
    @Autowired
    private RedisUtils redisUtils;

    @RequestMapping({"/", "/index"})
    public String root() {
        return "index";
    }


    /**
     * @PathVariable: 获取路径参数。即url/{id}这种形式。
     * @RequestParam: 获取查询参数。即url?name=这种形式
     * @RequestBody: 获取post请求的body
     * @RequestHeader: 获取请求头参数
     * @CookieValue: 获取Cookie
     * 无注解:         可用实体来获取
     */
    @PostMapping(value = "/login")
    public Result login(@RequestBody Map<String, String> map) {
        System.out.println(map.get("username"));
        System.out.println(map.get("password"));
        System.out.println("user login .....");
//        String exception = (String) request.getAttribute("shiroLoginFailure");
//        System.out.println("exception=" + exception);
        Map<String, Object> result = new HashMap<>();
        User user = this.userRepository.findByUsername(map.get("username"));
        String token = JwtUtil.sign(user.getId(), user.getPassword());
        user.setToken(token);
        result = userService.getLoginUserAndMenuInfo(user);
        boolean saveRedis = redisUtils.set(token, user.getId(), 1, TimeUnit.DAYS);
        if (saveRedis) {
            logger.info("token存入redis成功");
            return Result.success(result);
        }
//        if (exception != null) {
//            if (UnknownAccountException.class.getName().equals(exception)) {
//                System.out.println("UnknownAccountException -- > 账号不存在：");
//                msg = "unknownAccount";
//            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
//                msg = "incorrectPassword";
//            } else if ("kaptchaValidateFailed".equals(exception)) {
//                System.out.println("kaptchaValidateFailed -- > 验证码错误");
//                msg = "kaptchaValidateFailed -- > 验证码错误";
//            } else {
//                msg = "else >> " + exception;
//                System.out.println("else -- >" + exception);
//            }
//        }
//        map.put("msg", msg);
        //认证成功由shiro框架自行处理
//        return Result.success(result);
        return Result.error(HttpStatus.INTERNAL_SERVER_ERROR, "token存入redis失败");
    }


    @PostMapping("/get_info")
    public Result getUserInfoByToken(@RequestBody @Valid Map<String, String> map) {
        String token = map.get("token");
        System.out.println(token);
        if(token!=null){
            if (redisUtils.exists(token)) {
                Map<String, Object> result = new HashMap<>();
                String userId = JwtUtil.getUserId(token);
                if (userId == null) {
                    return Result.error(HttpStatus.FORBIDDEN, "token失效");
                }
                Optional<User> user = this.userRepository.findById(userId);
                if (!user.isPresent()) {//表示user为null
                    return Result.error(HttpStatus.FORBIDDEN, "token过期");
                }
                result.put("user", user.get());
                List<Menu> menuList = userService.getMenuListByUser(user.get());
                result.put("menuList", menuList);
                return Result.success(result);
            } else {
                return Result.error(HttpStatus.FORBIDDEN, "token失效");
            }
        }else {
            return Result.error(HttpStatus.FORBIDDEN, "token为空");
        }


    }

    //获取该用户的菜单
    @GetMapping("/get_router")
    public Result getRouter(@RequestParam String token) {
        String userId = JwtUtil.getUserId(token);
        if (userId==null) {
            return Result.error(HttpStatus.FORBIDDEN, "无效的token");
        }
        Optional<User> user = this.userRepository.findById(userId);
        if (!user.isPresent()) {//表示user为null
            return Result.error(HttpStatus.FORBIDDEN, "过期的token");
        }
        List<Menu> menuList = userService.getMenuListByUser(user.get());
        return Result.success(menuList);
    }

    //退出登录，删除redis中的token
    @PostMapping("/logout")
    public Result logout(@RequestBody Map<String, String> map) {
        String token = map.get("token");
        boolean b = redisUtils.remove(token);
        if (b) {
            return Result.success("退出登录成功");
        } else {
            return Result.error(HttpStatus.INTERNAL_SERVER_ERROR, "token删除失败");
        }
    }

    //访问此连接时会触发MyShiroRealm中的权限分配方法
    @RequestMapping("/permission")
    @RequiresPermissions("student:test")
    public void test() {
        System.out.println("permission  test");
    }
}
